<template>
  <div>
    <!-- 头部 -->
    <van-nav-bar
      title="修改密码"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 原密码 -->
    <van-field
      v-model="opwd"
      placeholder="请输入原密码"
      label="原密码"
      input-align="right"
      @blur="checkopwd"
      type="password"
    />
    <!-- 新密码 -->
    <van-field
      v-model="npwd"
      placeholder="请输入新密码"
      label="新密码"
      input-align="right"
      @blur="checknpwd"
      type="password"
    />
    <!-- 确认密码 -->
    <van-field
      v-model="dbnpwd"
      placeholder="请确认新密码"
      label="确认新密码"
      input-align="right"
      type="password"
      @blur="checkdbnpwd"
    />

    <van-button plain type="info" class="cancel" to="/mine">取消</van-button>
    <van-button type="info" @click="submit" class="con">确认</van-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      opwd: "",
      npwd: "",
      dbnpwd: "",
    };
  },
  methods: {
    // 返回上一页
    onClickLeft() {
      this.$router.go(-1);
    },
    // 验证旧密码
    checkopwd() {
      let url = "/checkopwd";
      let params = `username=${window.sessionStorage.getItem("name")}&opwd=${
        this.opwd
      }`;
      this.axios.post(url, params).then((res) => {
        if (res.data.code !== 200) {
          this.$toast("密码有误,请重新输入");
          return 0;
        }
        return 1;
      });
    },
    // 验证新密码格式
    checknpwd() {
      let check = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,16}$/;
      if (!check.test(this.npwd)) {
        this.$toast("密码有误,密码必须包含大小写字母和数字,长度需为6~16字符");
        return 0;
      }
      return 1;
    },
    // 确认新密码
    checkdbnpwd() {
      let check = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,16}$/;
      if (!check.test(this.dbnpwd) || this.dbnpwd != this.npwd) {
        this.$toast("密码不相同");
        return 0;
      }
      return 1;
    },

    // 确认修改
    submit() {
      if ( this.checknpwd() && this.checkdbnpwd()) {
        let url = "/password";
        let params = `username=${window.sessionStorage.getItem(
          "name"
        )}&password=${this.npwd}`;
        console.log(params);
        this.axios.post(url,params).then((res) => {
          if (res.data.code == 200) {
            this.$toast("修改成功");
          } else {
            this.$toast("修改失败");
          }
        });
      }
    },
  },
};
</script>
<style scoped>
.con {
  position: fixed;
  bottom: 50px;
  right: 0;
  width: 80%;
}
.cancel {
  position: fixed;
  bottom: 50px;
  left: 0;
  width: 20%;
}
</style>
